import { HttpCode } from '#/utils/contacts.js';
import deleteTacticSvg from '@/assets/ListingTransactionDeclaration/delete.svg';
import { PageLoading, TRAlert, TRDefault } from '@/components/index.js';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import {
  EditOutlined,
  FileTextOutlined,
  PlusCircleOutlined,
  UndoOutlined,
} from '@ant-design/icons';
import { useSetState } from 'ahooks';
import { Button, Card, Col, Divider, message, Row, Select, Spin, Tag } from 'antd';
import React, { useEffect } from 'react';
import { connect } from 'umi';
import { LABELS, UNITS } from './components/dictionary';
import type {
  CardDataType,
  SearchDataType,
  ListingTransactionDeclarationType,
} from './components/type';
import styles from './index.less';
import { saveListingData, saveWindow } from './services';
import type { FormProps } from 'antd';
import dayjs from 'dayjs';
import Plan from './components/Model/Plan';
import Windows from './components/Model/Windows';
import { CardDetail, InfoItem, havePermissions } from './helper';

const { Option } = Select;

const defaultState = {
  windowsNameSel: undefined,
  windowSetVisible: false,
  addVisible: false,
  windowName: null, // 窗口名称
  /* 默认参数 */
  modelTitle: '新增',
  stationIds: [],
  init: false,
};
const ListingTransactionDeclaration: React.FC<ListingTransactionDeclarationType> = ({
  menuCode,
  userName,
  buttonPermissions,
  list,
  cardListData,
  titleInfo,
  windowNameLength,
  dispatch,
}) => {
  const [state, setState] = useSetState({ ...defaultState });
  const [data, setData] = useSetState<{
    loading: boolean;
    spinLoding: boolean;
    error: string;
    cardListData: CardDataType[];
    editValue: any;
  }>({
    loading: true,
    spinLoding: true,
    error: '',
    cardListData: [],
    editValue: {},
  });
  // 交易中心
  const { treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${menuCode}/t_station`,
    (parmas) => {
      const stationIds = parmas.stations.map((v: any) => v.stationId);
      setState({ stationIds: stationIds });
      dispatch({
        type: 'ListingTransactionDeclaration/getStationIdList',
        payload: stationIds,
      });
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );

  const { spinLoding, error, loading } = data;

  useEffect(() => {
    dispatch({
      type: 'ListingTransactionDeclaration/fetchWindowSelectList',
      payload: {
        marketId: 'GXCSG',
      },
    });
    setState({ init: true });
  }, []);

  useEffect(() => {
    if (state.init && list.length > 0) {
      const id = state.windowsNameSel ? state.windowsNameSel : list[0].windowId;
      dispatch({
        type: 'ListingTransactionDeclaration/fetchData',
        payload: {
          marketId: 'GXCSG',
          stationIds: state.stationIds,
          windowId: id,
        },
      });
      setData({ spinLoding: false, loading: true });
      setState({ init: false, windowsNameSel: id });
    }
  }, [list, state.init]);

  useEffect(() => {
    setData({
      error: !list?.length ? '暂无窗口数据' : '',
      loading: false,
      cardListData: cardListData,
    });
  }, [cardListData]);

  const handleSearch =
    (data: SearchDataType) => async (event: React.MouseEvent<HTMLButtonElement>) => {
      event.preventDefault();
      try {
        setData({ loading: true, error: '' });
        const { stationIds, windowsNameSel } = data;
        const params = {
          marketId: 'GXCSG',
          stationIds,
          windowId: windowsNameSel ? windowsNameSel : null,
        };
        dispatch({
          type: 'ListingTransactionDeclaration/fetchData',
          payload: params,
        });
      } catch (error) {
        message.error('操作失败，请重试');
      }
    };

  // 弹窗
  const onCancelWindowSetVisible = () => {
    setState({
      windowSetVisible: !state.windowSetVisible,
    });
  };

  const onCancelAddVisible = () => {
    setState({
      addVisible: !state.addVisible,
    });
  };

  const onWindowsFinish: FormProps['onFinish'] = async (values) => {
    try {
      // 需求固定广西数据
      const params = {
        marketId: 'GXCSG',
        dynamicFields: {
          windowId: values.windowType === 'edit' ? values.windowEdit : null,
          windowName: values.windowName,
          startMarkDate: dayjs(values.marketDate[0]).format('YYYYMMDD'),
          endMarkDate: dayjs(values.marketDate[1]).format('YYYYMMDD'),
          reportDate: dayjs(values.reportDate).format('YYYYMMDD'),
          startReportTime: dayjs(values.reportTime[0]).format('HH:mm'),
          endReportTime: dayjs(values.reportTime[1]).format('HH:mm'),
        },
      };
      const res = await saveWindow(params);
      if (res.statusCode === HttpCode.SUCCESS) {
        message.success('窗口设置成功');
        dispatch({
          type: 'ListingTransactionDeclaration/fetchWindowSelectList',
          payload: {
            marketId: 'GXCSG',
          },
        });
        setState({
          windowSetVisible: !state.windowSetVisible,
          init: true,
        });
      } else {
        message.error(res.message);
      }
    } catch (error) {
      message.error('窗口配置失败');
    }
  };

  const onAddFinish: FormProps['onFinish'] = async (values) => {
    if (!values) return;
    const {
      id,
      scenarioName,
      minQuantity,
      maxQuantity,
      minPrice,
      maxPrice,
      totalDelisted,
      stationIds,
    } = values;

    const isAdd = state.modelTitle === '新增';

    const params = {
      marketId: 'GXCSG',
      dynamicFields: {
        userName,
        windowId: isAdd ? scenarioName : state.windowsNameSel,
        minQuantity,
        maxQuantity,
        minPrice,
        maxPrice,
        totalDelisted,
        stationIds: isAdd ? stationIds : undefined,
        operationType: isAdd ? 1 : 2,
        ...(isAdd ? {} : { planId: id }),
      },
    };

    try {
      if (!havePermissions('ListingDeclarationPlanAdd', buttonPermissions))
        return message.warning(`无方案${isAdd ? '新增' : '编辑'}权限`);

      const res = await saveListingData(params);
      if (res.statusCode === HttpCode.SUCCESS) {
        message.success(`方案${isAdd ? '新增' : '编辑'}成功`);
        setState({
          addVisible: false,
          init: true,
        });
      } else {
        message.error(res.message);
      }
    } catch (error) {
      message.error(`方案${isAdd ? '新增' : '编辑'}失败`);
    }
  };

  const deleteTacticFun =
    (delData: CardDataType) => (event: React.MouseEvent<HTMLImageElement>) => {
      event.preventDefault();
      if (!havePermissions('ListingDeclarationPlanDel', buttonPermissions))
        return message.warning('无方案撤销权限');
      TRAlert.show('确定撤销此方案？')
        .then(async (res: any) => {
          if (res.index === 1) {
            try {
              const params = {
                marketId: 'GXCSG',
                dynamicFields: {
                  userName,
                  planId: delData.id,
                  windowId: state.windowsNameSel,
                  operationType: 4,
                },
              };

              const res = await saveListingData(params);
              if (res.statusCode === HttpCode.SUCCESS) {
                message.success('方案撤销成功');
                setState({ init: true });
              } else {
                message.error(res.message);
              }
            } catch (error) {
              message.error('方案撤销失败');
            }
          }
        })
        .catch(() => {
          message.error('撤销操作失败，请重试');
        });
    };

  const cardAddFn = () => () => {
    setState({
      addVisible: !state.addVisible,
      modelTitle: '新增',
    });
    setData({ editValue: {} });
  };

  const cardEditFn = (data: CardDataType) => () => {
    setState({
      addVisible: !state.addVisible,
      modelTitle: '编辑',
    });
    if (data) {
      setData({ editValue: data });
    }
  };

  const headBox = () => {
    return (
      <>
        <div className={styles.headLeft}>
          <Select
            className={styles.nameSelect}
            style={{ width: windowNameLength * 15 }}
            value={state.windowsNameSel}
            placeholder="窗口名称"
            maxTagCount="responsive"
            onChange={(v: any) => setState({ windowsNameSel: v })}
          >
            {list?.map((item) => {
              return (
                <Option value={item.windowId} key={item.windowId}>
                  {item.windowName}
                </Option>
              );
            })}
          </Select>
          <div style={{ width: 200, marginLeft: 16 }}>
            {/* 目前这个页面固定广西数据源 */}
            <TjMarketingUnit
              value={state.stationIds}
              treeData={treeData}
              marketId={'GXCSG'}
              onChange={(ids: any) => {
                setState({
                  stationIds: ids,
                });
              }}
            />
          </div>
          <Button
            disabled={!havePermissions('ListingDeclarationQuery', buttonPermissions)}
            className={styles.queryBtn}
            type="primary"
            onClick={handleSearch(state)}
          >
            查询
          </Button>
        </div>
        <div className={styles.headRight}>
          <Button
            icon={<FileTextOutlined />}
            type="link"
            onClick={() =>
              setState({
                windowSetVisible: !state.windowSetVisible,
              })
            }
            disabled={!havePermissions('ListingDeclarationWindowAdd', buttonPermissions)}
          >
            窗口设置
          </Button>
          <Button
            disabled={!havePermissions('ListingDeclarationPlanAdd', buttonPermissions)}
            icon={<PlusCircleOutlined />}
            type="link"
            onClick={cardAddFn()}
            style={{ margin: '0 -16px' }}
          >
            新增
          </Button>
        </div>
      </>
    );
  };

  const bodyList = () => {
    return (
      <div className={styles.box}>
        <div className={styles.content}>
          <div className={styles.title}>
            <p style={{ display: 'flex' }}>
              <span className={styles.titleInfo}>约束信息 </span>
              <div>
                <InfoItem
                  label={LABELS.MIN_QUANTITY}
                  value={titleInfo?.minDeclareElectricty}
                  unit={UNITS.DELISTED}
                />
                {!titleInfo?.proxy && (
                  <>
                    <InfoItem
                      label={LABELS.MAX_PRICE}
                      value={titleInfo?.contractPriceLimit}
                      unit={UNITS.POWER}
                    />
                    <InfoItem
                      label={LABELS.MIN_PRICE}
                      value={titleInfo?.contractPriceLowerLimit}
                      unit={UNITS.POWER}
                    />
                  </>
                )}
                <InfoItem label={LABELS.SPOT_DATE} value={titleInfo?.spotOperatingDay} />
                <InfoItem
                  label={LABELS.QUANTITY_UNIT}
                  value={titleInfo?.minCapacity}
                  unit={UNITS.DELISTED}
                />
                <InfoItem
                  label={LABELS.PRICE_UNIT}
                  value={titleInfo?.minEletricPrice}
                  unit={UNITS.POWER}
                />
              </div>
            </p>
          </div>
          <div className={styles.title}>
            <p style={{ display: 'flex' }}>
              <span className={styles.titleInfo}>市场总体情况</span>
              <div>
                <InfoItem
                  label={LABELS.TRANSACTION_ELECTRICITY}
                  value={titleInfo?.tradedElectricity}
                  unit={UNITS.DELISTED}
                  className={styles.numberT}
                />
                <InfoItem
                  label={LABELS.LISTED_ELECTRICITY}
                  value={titleInfo?.listingElectricity}
                  unit={UNITS.DELISTED}
                  className={styles.numberT}
                />
              </div>
            </p>
          </div>
          <Divider style={{ margin: '0 0 8px 0' }} />
          <div style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', paddingRight: 10 }}>
            <Spin style={{ height: '100%' }} spinning={data.loading}>
              {data.cardListData?.length > 0 ? (
                <Row gutter={16}>
                  {data.cardListData.map((card, index: number) => (
                    <Col span={8} key={card.id}>
                      {/* <div className={styles.delete}>
                        <img src={deleteTacticSvg} alt={''} onClick={deleteTacticFun(card)} />
                      </div> */}
                      <Card bordered={false} className={styles.cardBox}>
                        <div className={styles.cardContent}>
                          <div className={styles.cardTitle}>
                            <span className={styles.titleName}>
                              {card.scenarioName}{' '}
                              {card.statusDesc && <Tag color="gold">{card.statusDesc}</Tag>}
                            </span>
                            <div>
                              {!card.statusDesc && (
                                <>
                                  <Button
                                    icon={<EditOutlined />}
                                    type="link"
                                    onClick={cardEditFn(card)}
                                  >
                                    编辑
                                  </Button>
                                  <Button
                                    icon={<UndoOutlined />}
                                    type="link"
                                    onClick={deleteTacticFun(card)}
                                    style={{ margin: '0 -16px' }}
                                  >
                                    撤销
                                  </Button>
                                </>
                              )}
                            </div>
                          </div>
                          <div className={styles.cardInfo}>
                            <p>本企业成交情况</p>
                            <CardDetail card={card} proxy={titleInfo?.proxy} />
                          </div>
                        </div>
                      </Card>
                    </Col>
                  ))}
                </Row>
              ) : (
                <TRDefault type="emptysm" />
              )}
            </Spin>
          </div>
        </div>
      </div>
    );
  };

  // 权限控制
  // if (spinLoding) return <PageLoading />;
  // if (error) return <TRDefault type="error" message={error} />;
  return (
    <div className={styles.container}>
      <div className={styles.head}>{headBox()}</div>
      {error ? <TRDefault type="error" message={error} /> : bodyList()}
      <Windows
        state={state}
        onCancelWindowSetVisible={onCancelWindowSetVisible}
        onFinish={onWindowsFinish}
      />
      <Plan
        treeData={treeData}
        state={state}
        onCancelAddVisible={onCancelAddVisible}
        onFinish={onAddFinish}
        editValue={data.editValue}
      />
    </div>
  );
};

export default connect(({ global, ListingTransactionDeclaration }: any) => ({
  buttonPermissions: global.configure.buttonPermissions,
  menuCode: global.configure.menuCode,
  userName: global.configure.currentUser.name,
  list: ListingTransactionDeclaration.list,
  cardListData: ListingTransactionDeclaration.cardListData,
  titleInfo: ListingTransactionDeclaration.titleInfo,
  windowNameLength: ListingTransactionDeclaration.windowNameLength,
}))(ListingTransactionDeclaration);
